<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="编码" prop="invCode">
        <el-input
          v-model="queryParams.invCode"
          placeholder="请输入编码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="名称" prop="invName">
        <el-input
          v-model="queryParams.invName"
          placeholder="请输入名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="型号" prop="invModel">
        <el-select v-model="queryParams.invModel" placeholder="请选择型号" clearable size="small">
          <el-option
            v-for="dict in dict.type.sys_inv_model"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="规格" prop="invSpac">
        <el-select v-model="queryParams.invSpac" placeholder="请选择规格" clearable size="small">
          <el-option
            v-for="dict in dict.type.sys_inv_spac"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="可拆分" prop="separable">
        <el-select v-model="queryParams.separable" placeholder="请选择可拆分" clearable size="small">
          <el-option
            v-for="dict in dict.type.sys_yes_no"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="基本单位" prop="basicUnitCode">
        <el-select v-model="queryParams.basicUnitCode" placeholder="请选择基本单位" clearable size="small">
          <el-option
            v-for="dict in dict.type.base_measure_unit"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['base:inventory:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['base:inventory:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['base:inventory:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['base:inventory:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="inventoryList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" v-if="true"/>
      <el-table-column label="商品根级类型" align="center" prop="invRootTypeId" />
      <el-table-column label="商品类型" align="center" prop="invTypeId" />
      <el-table-column label="编码" align="center" prop="invCode" />
      <el-table-column label="名称" align="center" prop="invName" />
      <el-table-column label="型号" align="center" prop="invModel">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_inv_model" :value="scope.row.invModel"/>
        </template>
      </el-table-column>
      <el-table-column label="规格" align="center" prop="invSpac">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_inv_spac" :value="scope.row.invSpac"/>
        </template>
      </el-table-column>
      <el-table-column label="可拆分" align="center" prop="separable">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.separable"/>
        </template>
      </el-table-column>
      <el-table-column label="基本单位" align="center" prop="basicUnitCode">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.base_measure_unit" :value="scope.row.basicUnitCode"/>
        </template>
      </el-table-column>
      <el-table-column label="单位组" align="center" prop="groupUnitCode" />
      <el-table-column label="计价方式" align="center" prop="valueType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.base_value_type" :value="scope.row.valueType"/>
        </template>
      </el-table-column>
      <el-table-column label="机构id" align="center" prop="orgId" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['base:inventory:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['base:inventory:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改商品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width=600px append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
           <el-col :span=12>
            <el-form-item label="编码" prop="invCode">
              <el-input v-model="form.invCode" placeholder="请输入编码" />
            </el-form-item>
           </el-col>
           <el-col :span=12>
            <el-form-item label="名称" prop="invName">
              <el-input v-model="form.invName" placeholder="请输入名称" />
            </el-form-item>
           </el-col>
        </el-row>
        <el-row>
           <el-col :span=12>
            <el-form-item label="型号" prop="invModel">
              <el-select v-model="form.invModel" placeholder="请选择型号">
                <el-option
                  v-for="dict in dict.type.sys_inv_model"
                  :key="dict.value"
                  :label="dict.label"
:value="dict.value"                ></el-option>
              </el-select>
            </el-form-item>
           </el-col>
           <el-col :span=12>
            <el-form-item label="规格" prop="invSpac">
              <el-select v-model="form.invSpac" placeholder="请选择规格">
                <el-option
                  v-for="dict in dict.type.sys_inv_spac"
                  :key="dict.value"
                  :label="dict.label"
:value="dict.value"                ></el-option>
              </el-select>
            </el-form-item>
           </el-col>
        </el-row>
        <el-row>
           <el-col :span=12>
            <el-form-item label="可拆分">
              <el-radio-group v-model="form.separable">
                <el-radio
                  v-for="dict in dict.type.sys_yes_no" :key="dict.value"
:label="dict.value"                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
           </el-col>
           <el-col :span=12>
            <el-form-item label="基本单位" prop="basicUnitCode">
              <el-select v-model="form.basicUnitCode" placeholder="请选择基本单位">
                <el-option
                  v-for="dict in dict.type.base_measure_unit"
                  :key="dict.value"
                  :label="dict.label"
:value="dict.value"                ></el-option>
              </el-select>
            </el-form-item>
           </el-col>
        </el-row>
        <el-row>
        </el-row>
        <el-row>
           <el-col :span=12>
            <el-form-item label="提前期" prop="invAdvance">
              <el-input-number v-model="form.invAdvance" placeholder="请输入提前期 " :min="0"/>
            </el-form-item>
           </el-col>
           <el-col :span=12>
            <el-form-item label="计价方式" prop="valueType">
              <el-select v-model="form.valueType" placeholder="请选择计价方式">
                <el-option
                  v-for="dict in dict.type.base_value_type"
                  :key="dict.value"
                  :label="dict.label"
:value="dict.value"                ></el-option>
              </el-select>
            </el-form-item>
           </el-col>
        </el-row>
        <el-row>
        </el-row>
        <el-row>
           <el-col :span=12>
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in dict.type.sys_normal_disable" :key="dict.value"
:label="dict.value"                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
           </el-col>
    <el-col :span=12>
        <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
    </el-col>
        <el-divider content-position="center">商品扩展信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddInventoryDetail">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteInventoryDetail">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="inventoryDetailList" :row-class-name="rowInventoryDetailIndex" @selection-change="handleInventoryDetailSelectionChange" ref="inventoryDetail">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="条码" prop="barCode">
            <template slot-scope="scope">
              <el-input v-model="scope.row.barCode" placeholder="请输入条码" />
            </template>
          </el-table-column>
          <el-table-column label="单位" prop="unitCode">
            <template slot-scope="scope">
              <el-input v-model="scope.row.unitCode" placeholder="请输入单位" />
            </template>
          </el-table-column>
          <el-table-column label="多属性" prop="sku">
            <template slot-scope="scope">
              <el-input v-model="scope.row.sku" placeholder="请输入多属性" />
            </template>
          </el-table-column>
          <el-table-column label="采购价" prop="phPrice">
            <template slot-scope="scope">
              <el-input v-model="scope.row.phPrice" placeholder="请输入采购价" />
            </template>
          </el-table-column>
          <el-table-column label="销售价" prop="saPrice">
            <template slot-scope="scope">
              <el-input v-model="scope.row.saPrice" placeholder="请输入销售价" />
            </template>
          </el-table-column>
          <el-table-column label="零售价" prop="retailPrice">
            <template slot-scope="scope">
              <el-input v-model="scope.row.retailPrice" placeholder="请输入零售价" />
            </template>
          </el-table-column>
          <el-table-column label="标准成本" prop="normalCost">
            <template slot-scope="scope">
              <el-input v-model="scope.row.normalCost" placeholder="请输入标准成本" />
            </template>
          </el-table-column>
          <el-table-column label="最新成本" prop="newCost">
            <template slot-scope="scope">
              <el-input v-model="scope.row.newCost" placeholder="请输入最新成本" />
            </template>
          </el-table-column>
          <el-table-column label="采购价上限" prop="phLimitPrice">
            <template slot-scope="scope">
              <el-input v-model="scope.row.phLimitPrice" placeholder="请输入采购价上限" />
            </template>
          </el-table-column>
          <el-table-column label="销售价下限" prop="saLimitPrice">
            <template slot-scope="scope">
              <el-input v-model="scope.row.saLimitPrice" placeholder="请输入销售价下限" />
            </template>
          </el-table-column>
          <el-table-column label="安全库存数" prop="safeNum">
            <template slot-scope="scope">
              <el-input v-model="scope.row.safeNum" placeholder="请输入安全库存数" />
            </template>
          </el-table-column>
          <el-table-column label="库存上限" prop="maxNum">
            <template slot-scope="scope">
              <el-input v-model="scope.row.maxNum" placeholder="请输入库存上限" />
            </template>
          </el-table-column>
          <el-table-column label="库存下限" prop="minNum">
            <template slot-scope="scope">
              <el-input v-model="scope.row.minNum" placeholder="请输入库存下限" />
            </template>
          </el-table-column>
          <el-table-column label="机构id" prop="orgId">
            <template slot-scope="scope">
              <el-input v-model="scope.row.orgId" placeholder="请输入机构id" />
            </template>
          </el-table-column>
          <el-table-column label="状态" prop="status">
            <template slot-scope="scope">
              <el-input v-model="scope.row.status" placeholder="请输入状态" />
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="remark">
            <template slot-scope="scope">
              <el-input v-model="scope.row.remark" placeholder="请输入备注" />
            </template>
          </el-table-column>
        </el-table>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm(false)">保 存</el-button>
        <el-button :loading="buttonLoading" type="primary" @click="submitForm(true)">保存并新增</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listInventory, getInventory, delInventory, addInventory, updateInventory } from "@/api/base/inventory";
import { getCode } from "@/api/sys/codeRule";

export default {
  name: "Inventory",
  dicts: ['sys_inv_model', 'sys_inv_spac', 'base_measure_unit', 'base_value_type', 'sys_yes_no', 'sys_normal_disable'],
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedInventoryDetail: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品表格数据
      inventoryList: [],
      // 商品扩展表格数据
      inventoryDetailList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        invRootTypeId: undefined,
        invTypeId: undefined,
        invCode: undefined,
        invName: undefined,
        invModel: undefined,
        invSpac: undefined,
        separable: undefined,
        basicUnitCode: undefined,
        groupUnitCode: undefined,
        orgId: undefined,
        status: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        id: [
          { required: true, message: "编号不能为空", trigger: "blur" }
        ],
        invRootTypeId: [
          { required: true, message: "商品根级类型不能为空", trigger: "change" }
        ],
        invTypeId: [
          { required: true, message: "商品类型不能为空", trigger: "change" }
        ],
        invCode: [
          { required: true, message: "编码不能为空", trigger: "blur" }
        ],
        invName: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        invModel: [
          { required: true, message: "型号不能为空", trigger: "change" }
        ],
        invSpac: [
          { required: true, message: "规格不能为空", trigger: "change" }
        ],
        separable: [
          { required: true, message: "可拆分不能为空", trigger: "blur" }
        ],
        basicUnitCode: [
          { required: true, message: "基本单位不能为空", trigger: "change" }
        ],
        groupUnitCode: [
          { required: true, message: "单位组不能为空", trigger: "change" }
        ],
        valueType: [
          { required: true, message: "计价方式不能为空", trigger: "change" }
        ],
        orgId: [
          { required: true, message: "机构id不能为空", trigger: "change" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询商品列表 */
    getList() {
      this.loading = true;
      listInventory(this.queryParams).then(response => {
        this.inventoryList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 保存并新增操作 */
    handleSaveAdd() {
      this.reset();
      this.form.invCode = getCode('1001',null).then(response => {
        return response.data;
      });
      this.getTreeselect();
      this.title = "添加商品";
    },
    // 表单重置
    reset() {
      if (this.form.id != undefined && this.form.id != null && this.form.id != ''){
        // todo 回收编码
      }

      this.form = {
        id: undefined,
        invRootTypeId: undefined,
        invTypeId: undefined,
        invCode: undefined,
        invName: undefined,
        invModel: undefined,
        invSpac: undefined,
        separable: "0",
        basicUnitCode: undefined,
        groupUnitCode: undefined,
        invAdvance: undefined,
        valueType: undefined,
        orgId: undefined,
        status: "0",
        delFlag: undefined,
        remark: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        tenantId: undefined
      };
      this.inventoryDetailList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品";
      getCode('1001',null).then(response => {
        this.form.invCode = response.data;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getInventory(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.inventoryDetailList = response.data.inventoryDetailList;
        this.open = true;
        this.title = "修改商品";
      });
    },
    /** 提交按钮 */
    submitForm(isAdd) {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          this.form.inventoryDetailList = this.inventoryDetailList;
          if (this.form.id != null) {
            updateInventory(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              if (isAdd){
                  this.handleSaveAdd();
              }else {
                  this.open = false;
              }
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addInventory(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              if (isAdd){
                  this.handleSaveAdd();
              }else {
                  this.open = false;
              }
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除商品编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delInventory(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).finally(() => {
        this.loading = false;
      });
    },
	/** 商品扩展序号 */
    rowInventoryDetailIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 商品扩展添加按钮操作 */
    handleAddInventoryDetail() {
      let obj = {};
      obj.barCode = "";
      obj.unitCode = "";
      obj.sku = "";
      obj.phPrice = "";
      obj.saPrice = "";
      obj.retailPrice = "";
      obj.normalCost = "";
      obj.newCost = "";
      obj.phLimitPrice = "";
      obj.saLimitPrice = "";
      obj.safeNum = "";
      obj.maxNum = "";
      obj.minNum = "";
      obj.orgId = "";
      obj.status = "";
      obj.remark = "";
      this.inventoryDetailList.push(obj);
    },
    /** 商品扩展删除按钮操作 */
    handleDeleteInventoryDetail() {
      if (this.checkedInventoryDetail.length == 0) {
        this.$modal.msgError("请先选择要删除的商品扩展数据");
      } else {
        const inventoryDetailList = this.inventoryDetailList;
        const checkedInventoryDetail = this.checkedInventoryDetail;
        this.inventoryDetailList = inventoryDetailList.filter(function(item) {
          return checkedInventoryDetail.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleInventoryDetailSelectionChange(selection) {
      this.checkedInventoryDetail = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('base/inventory/export', {
        ...this.queryParams
      }, `inventory_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
